<template>
  <div class="container">
    <div class="batch">
      <a-row>
        <a-col :span="4">
          <planUnit :form.sync="planUnitForm" @changeRecommend="changeRecommend"/>
        </a-col>
        <a-col :span="4" class="offset">
          <originality :form.sync="originalityForm" :describe="describe" />
        </a-col>
        <a-col :span="8" class="offset">
          <pic :form.sync="picForm"  />
        </a-col>
        <a-col :span="8" class="offset">
          <myVideo :form.sync="myVideoForm" />
        </a-col>
      </a-row>
      <a-popconfirm title="确定提交？" ok-text="提交" cancel-text="取消" @confirm='submitSync'>
        <a-button type="primary" :loading="loading" style="margin-top: 20px;">
          {{ submitBtnName }}
        </a-button>
      </a-popconfirm>
      <a-popconfirm title="确定返回？" ok-text="返回" cancel-text="取消" @confirm='back' style="margin-left: 5px;">
        <a-button style="box-sizing: content-box;">返回</a-button>
      </a-popconfirm>
      <a-tooltip v-if="last_time" style="margin-left: 10px;">
        <template slot="title">
          <span>上次提交时间：{{ last_time }}</span>
        </template>
        <a-icon type="info-circle" />
      </a-tooltip>
    </div>
  </div>
</template>

<script>
import planUnit from './components/planUnit'
import originality from './components/originality'
import pic from './components/pic'
import myVideo from './components/video'
import {oneClickCreate,asyncOneClickCreate,getLastSubmitTime} from '@/api/dianshang/dianshang'
export default {
  data() {
    return {
      planUnitForm:{},
      originalityForm:{},
      picForm: [],
      myVideoForm: [],
      loading:false,
      describe: [],
      taskCount: 0,
      taskIndex: 0,
      last_time:'',
    }
  },
  created() {
    this.getLastSubmitTime()
  },
  methods:{
    submit(){
      // console.log(this.planUnitForm, this.originalityForm, this.picForm, this.myVideoForm)
      let params = {
        ...this.planUnitForm,
        ...this.originalityForm,
        picList: this.picForm,
        videoList: this.myVideoForm
      }
      let fd = this.getFormData(params)
      // for (let [a, b] of fd.entries()) {
      //   console.log(a, b, '--------------');
      // } 
      this.loading = true
      oneClickCreate(fd).then((res) => {
        // console.log(res)
        this.loading = false
        if(res.errcode == 0){
          this.$message.success('提交成功')
        }
      }).catch((err) => {
        console.log(err)
        this.loading = false
      });
    },
    async submitSync(){
      let status = 'success'
      let params = {
        ...this.planUnitForm,
        ...this.originalityForm,
        picList: this.picForm,
        videoList: this.myVideoForm
      }
      if (!this.check(params)) { return; }
      console.log(params);
      let funcList = []
      funcList = this.getFuncList(params) //根据视频数量生成计划任务
      this.loading = true
      // console.log(params, destAccountIds, funcList, asyncOneClickCreate)
      await funcList.reduce(
        (preFunc, obj) => preFunc.then(() => {
          this.taskIndex++;
          let data = {
            ...this.planUnitForm,
            ...this.originalityForm,
            picList: this.picForm,
            videoList: this.myVideoForm
          }
          Object.assign(data, obj.data)
          let fd = this.getFormData(data)
          return obj.func(fd)
        }).catch((err) => {
          console.log(err)
          status = 'error'
          this.loading = false
        }),
        Promise.resolve()
      ) 
      this.loading = false
      this.taskIndex = 0;
      if(status == 'success'){
        this.$message.success('一键创建商品计划已成功放入队列^_^')
        this.getLastSubmitTime()
      }
    },
    getFormData(params){
      var fd = new FormData();
      for(let [key, value] of Object.entries(params)){
        if(key == "picList"){
          for(let [, i] of Object.entries(value)){
            // console.log(key+idx, i)
            // fd.append(key+"["+idx+"]", i)
            // let fileName = new Date().valueOf() + Math.floor(Math.random()*(100000-1)+1) + '.' +i.type.split('/')[1]
            fd.append(key+"[]", i.blob, i.name)
          }
        }else if(key == 'userPortrait'){
          if(value.blob == ""){break;}
          fd.append(key+"[]", value.blob, value.name)
        }else if(key == 'custom' || key == 'program' || key == 'zhibo'){
          let v = {}
          value.forEach(e => {
            v[e['key']] = e
          });
          fd.append(key, JSON.stringify(v))
        }else if(key == 'videoList'){
          fd.append(key, JSON.stringify(value))
        }else if(key == 'biaoti' || key == 'describe'){
          fd.append(key, value.join('||'))
        }
        else{
          fd.append(key, value)
        }
      }
      return fd
    },
    getLastSubmitTime() {
      getLastSubmitTime().then((res) => {
        if (res.errcode == 0) {
          this.last_time = res.data.last_time
        }
      }).catch(() => {
        
      });
    },
    getFuncList(params) {
      const videoList = params.videoList
      const videoProgram = params.program.find(e => e.key == "video")
      const video_source = params.video_source
      const destAccountIds = params.destAccountIds
      const videoType = params.videoType // 1: 随机模式；2：独立视频（账户下的计划的视频一致，不同账户视频不一样）
      const videoProgramCount = videoProgram['value']
      let result = [];
      let taskCount = 0;
      if (video_source == 1 && videoProgram && videoProgramCount > 0) {
        const videoProgramCount = videoProgram['value']
        const destAccountIdsCount = destAccountIds.length
        let count; // 控制视频数，type = 2 还控制传入账户
        if (videoType == 2) {
          taskCount = count = destAccountIdsCount
          for (let idx = 0; idx < count; idx++){
            let start = idx * videoProgramCount
            let end = (idx + 1) * videoProgramCount
            result.push({
              func: asyncOneClickCreate,
              data: {
                videoList: videoList.slice(start, end),
                destAccountIds: [destAccountIds[idx]]
              }
            })
          }
        } else { 
          count = Math.floor(videoList.length / videoProgramCount)
          // 在type = 1的情况下，至多每3账户一组任务
          let d = 3
          let len = Math.ceil(destAccountIds.length / d)
          taskCount = count * len;
          for (let idx = 0; idx < count; idx++){
            let start = idx * videoProgramCount
            let end = (idx + 1) * videoProgramCount
            for (let o = 0; o < len; o++){
              result.push({
                func: asyncOneClickCreate,
                data: {
                  videoList: videoList.slice(start, end),
                  destAccountIds: destAccountIds.slice(d*o, d*(o+1))
                }
              })
            }
          }
        }
        this.taskCount = taskCount
      }else if (video_source != 1) {
        // 当视频来源不为本地上传时，执行操作
        result.push({
          func: asyncOneClickCreate,
          data: {
            videoList: [],
          }
        })
        this.taskCount = ++taskCount
      }
      return result;
    },
    check(params) {
      if (!params.program) {
        this.$message.warning('缺少参数')
        return false
      } else if (params.video_source == 1 && params.videoList.length == 0) {
        this.$message.warning('视频来源为本地上传时，视频不能为空')
        return false
      } else {
        return true
      }
    },
    changeRecommend(val){
      this.describe = val
    },
    back(){
      this.$router.back(-1)
    },
  },
  computed: {
    submitBtnName() {
      if (!this.loading) {
        return '异步提交'
      } else {
        return this.taskIndex + ' / ' + this.taskCount + ' 提交中'
      }
    }
  },
  components:{planUnit, originality, pic, myVideo}
}
</script>

<style lang="less" scoped>
.container{
  background-color: #f0f2f5;
  height: 100vh;
  overflow: hidden;
  .batch{
    width: 1460px;
    margin: 100px auto 0;
    // background-color: #ffffff;
    height: 450px;
  }
  .offset{
    margin-left: -1px;
  }
}
</style>
